<template>
    <div class="cart-container">
        <div class="page-header">
            <h1 class="page-title">购物车</h1>
            <p class="page-subtitle">管理您的购物车商品</p>
        </div>
        
        <div v-if="cartItems.length > 0" class="cart-content">
            <!-- 购物车列表 -->
            <div class="cart-list">
                <div class="list-header">
                    <el-checkbox
                        v-model="selectAll"
                        @change="handleSelectAll"
                        :indeterminate="isIndeterminate"
                    >
                        全选
                    </el-checkbox>
                    <span class="total-count">共 {{ cartItems.length }} 件商品</span>
                </div>
                
                <div class="cart-items">
                    <div
                        v-for="item in cartItems"
                        :key="item.id"
                        class="cart-item"
                    >
                        <el-checkbox
                            v-model="item.selected"
                            @change="handleSelectItem"
                        />
                        
                        <div class="item-image">
                            <img 
                                :src="item.image" 
                                :alt="item.name" 
                                @error="handleImageError"
                            />
                        </div>
                        
                        <div class="item-info">
                            <h3 class="item-name">{{ item.name }}</h3>
                            <p class="item-desc">{{ item.description }}</p>
                            <div class="item-specs">
                                <span v-for="spec in item.specifications" :key="spec" class="spec-tag">
                                    {{ spec }}
                                </span>
                            </div>
                            <div class="item-meta">
                                <span class="brand">品牌: {{ item.specifications[0] || '未知' }}</span>
                                <span class="category">{{ item.specifications[1] }} > {{ item.specifications[2] }}</span>
                            </div>
                        </div>
                        
                        <div class="item-price">
                            <span class="current-price">¥{{ item.price.toFixed(2) }}</span>
                            <span v-if="item.originalPrice" class="original-price">
                                ¥{{ item.originalPrice.toFixed(2) }}
                            </span>
                        </div>
                        
                        <div class="item-quantity">
                            <el-input-number
                                v-model="item.quantity"
                                :min="1"
                                :max="item.stock"
                                @change="updateQuantity(item)"
                                size="small"
                            />
                            <div class="stock-info">库存 {{ item.stock }} 件</div>
                        </div>
                        
                        <div class="item-subtotal">
                            <span class="subtotal-amount">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
                        </div>
                        
                        <div class="item-actions">
                            <el-button
                                type="text"
                                @click="addToFavorites(item)"
                                class="action-btn"
                            >
                                <el-icon><Star /></el-icon>
                                收藏
                            </el-button>
                            <el-button
                                type="text"
                                @click="removeItem(item)"
                                class="action-btn danger"
                            >
                                <el-icon><Delete /></el-icon>
                                删除
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 结算面板 -->
            <div class="checkout-panel">
                <div class="panel-header">
                    <h3>订单统计</h3>
                </div>
                
                <div class="panel-content">
                    <div class="summary-row">
                        <span class="label">已选商品 ({{ selectedItems.length }}件):</span>
                        <span class="value">¥{{ totalPrice.toFixed(2) }}</span>
                    </div>
                    
                    <div class="summary-row discount" v-if="discount > 0">
                        <span class="label">优惠减免:</span>
                        <span class="value">-¥{{ discount.toFixed(2) }}</span>
                    </div>
                    
                    <div class="summary-total">
                        <span class="label">应付总额:</span>
                        <span class="amount">¥{{ finalTotal.toFixed(2) }}</span>
                    </div>
                    
                    <div class="checkout-actions">
                        <el-button
                            type="primary"
                            size="large"
                            @click="goToCheckout"
                            :disabled="selectedItems.length === 0"
                            class="checkout-btn"
                        >
                            立即结算 ({{ selectedItems.length }})
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 空购物车状态 -->
        <div v-else class="empty-cart">
            <el-empty description="购物车是空的">
                <template #image>
                    <div class="empty-image">
                        <el-icon size="80"><ShoppingCart /></el-icon>
                    </div>
                </template>
                <template #description>
                    <p>购物车还是空的，快去挑选喜欢的商品吧！</p>
                </template>
                <el-button type="primary" @click="goToShopping">
                    去购物
                </el-button>
            </el-empty>
        </div>
        

    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Star, Delete, ShoppingCart } from '@element-plus/icons-vue'
import { getCart, changeCart, delCart } from '@/api/shopping'

const router = useRouter()

// 响应式数据
const cartItems = ref([])
const loading = ref(false)
const selectAll = ref(false)
const discount = ref(0)



// 计算属性
const selectedItems = computed(() => {
    return cartItems.value.filter(item => item.selected)
})

const isIndeterminate = computed(() => {
    const selectedCount = selectedItems.value.length
    return selectedCount > 0 && selectedCount < cartItems.value.length
})

const totalPrice = computed(() => {
    return selectedItems.value.reduce((sum, item) => {
        return sum + (item.price * item.quantity)
    }, 0)
})

const finalTotal = computed(() => {
    return Math.max(0, totalPrice.value - discount.value)
})

// 获取购物车数据
const fetchCartItems = async () => {
    loading.value = true
    try {
        const data = await getCart()
        console.log('购物车数据:', data) // 调试用
        cartItems.value = data.map(item => ({
            id: item.id,
            name: item.commodityDetail.name,
            description: item.commodityDetail.caption || '',
            price: parseFloat(item.commodityDetail.price),
            originalPrice: item.commodityDetail.original_price ? parseFloat(item.commodityDetail.original_price) : null,
            quantity: item.number,
            stock: item.commodityDetail.stock || 999,
            image:item.commodityDetail.commodityimg_set && item.commodityDetail.commodityimg_set.length > 0 
                ? `/file${item.commodityDetail.commodityimg_set[0].src}` 
                : '/placeholder.jpg',
            specifications: [item.commodityDetail.brand, item.commodityDetail.classification1_name, item.commodityDetail.classification2_name].filter(Boolean),
            selected: false,
            commodityId: item.commodity
        }))
        console.log('处理后的购物车数据:', cartItems.value) // 调试用
    } catch (error) {
        console.error('获取购物车失败:', error)
        ElMessage.error('获取购物车失败')
    } finally {
        loading.value = false
    }
}

// 全选/取消全选
const handleSelectAll = (value) => {
    cartItems.value.forEach(item => {
        item.selected = value
    })
}

// 选择单个商品
const handleSelectItem = () => {
    const selectedCount = selectedItems.value.length
    const totalCount = cartItems.value.length
    
    if (selectedCount === 0) {
        selectAll.value = false
    } else if (selectedCount === totalCount) {
        selectAll.value = true
    }
}

// 更新商品数量
const updateQuantity = async (item) => {
    try {
        await changeCart(item.id, { number: item.quantity })
        ElMessage.success('数量更新成功')
    } catch (error) {
        console.error('更新数量失败:', error)
        ElMessage.error('更新数量失败')
        // 重新获取购物车数据
        fetchCartItems()
    }
}

// 删除商品
const removeItem = async (item) => {
    try {
        await ElMessageBox.confirm('确定要删除这个商品吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        
        await delCart(item.id)
        ElMessage.success('删除成功')
        fetchCartItems()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除失败:', error)
            ElMessage.error('删除失败')
        }
    }
}

// 添加到收藏
const addToFavorites = (item) => {
    ElMessage.info('收藏功能开发中...')
}



// 跳转到结算页面
const goToCheckout = () => {
    if (selectedItems.value.length === 0) {
        ElMessage.warning('请选择要结算的商品')
        return
    }
    
    const selectedIds = selectedItems.value.map(item => item.id)
    router.push({
        name: 'Settle',
        query: { items: selectedIds.join(',') }
    })
}

// 跳转到购物页面
const goToShopping = () => {
    router.push({ name: 'Shopping' })
}

// 图片加载错误处理
const handleImageError = (event) => {
    event.target.src = '/placeholder.jpg'
}



onMounted(() => {
    fetchCartItems()
})
</script>

<style lang="less" scoped>
.cart-container {
    padding: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

.page-header {
    margin-bottom: 30px;
    text-align: center;
    
    .page-title {
        font-size: 32px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 8px;
    }
    
    .page-subtitle {
        color: #7f8c8d;
        font-size: 16px;
        margin: 0;
    }
}

.cart-content {
    display: grid;
    grid-template-columns: 1fr 320px;
    gap: 24px;
    align-items: start;
}

.cart-list {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    
    .list-header {
        padding: 20px 24px;
        background: #f8f9fa;
        border-bottom: 1px solid #ecf0f1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        
        .total-count {
            color: #7f8c8d;
            font-size: 14px;
        }
    }
    
    .cart-items {
        .cart-item {
            padding: 24px;
            border-bottom: 1px solid #ecf0f1;
            display: grid;
            grid-template-columns: auto 80px 1fr auto auto auto auto;
            gap: 16px;
            align-items: center;
            
            &:last-child {
                border-bottom: none;
            }
            
            .item-image {
                width: 80px;
                height: 80px;
                border-radius: 8px;
                overflow: hidden;
                
                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }
            
            .item-info {
                min-width: 0;
                
                .item-name {
                    font-size: 16px;
                    font-weight: 600;
                    color: #2c3e50;
                    margin-bottom: 8px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
                
                .item-desc {
                    color: #7f8c8d;
                    font-size: 14px;
                    margin-bottom: 8px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
                
                .item-specs {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 4px;
                    margin-bottom: 8px;
                    
                    .spec-tag {
                        background: #f8f9fa;
                        color: #7f8c8d;
                        padding: 2px 6px;
                        border-radius: 4px;
                        font-size: 12px;
                    }
                }
                
                .item-meta {
                    display: flex;
                    flex-direction: column;
                    gap: 2px;
                    font-size: 12px;
                    color: #95a5a6;
                    
                    .brand {
                        font-weight: 500;
                    }
                    
                    .category {
                        color: #7f8c8d;
                    }
                }
            }
            
            .item-price {
                text-align: right;
                
                .current-price {
                    font-size: 18px;
                    font-weight: 600;
                    color: #e74c3c;
                    display: block;
                }
                
                .original-price {
                    font-size: 14px;
                    color: #95a5a6;
                    text-decoration: line-through;
                }
            }
            
            .item-quantity {
                text-align: center;
                
                .stock-info {
                    font-size: 12px;
                    color: #95a5a6;
                    margin-top: 4px;
                }
            }
            
            .item-subtotal {
                text-align: right;
                
                .subtotal-amount {
                    font-size: 18px;
                    font-weight: 600;
                    color: #2c3e50;
                }
            }
            
            .item-actions {
                display: flex;
                flex-direction: column;
                gap: 8px;
                
                .action-btn {
                    padding: 4px 8px;
                    font-size: 12px;
                    
                    &.danger {
                        color: #e74c3c;
                        
                        &:hover {
                            color: #c0392b;
                        }
                    }
                }
            }
        }
    }
}

.checkout-panel {
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    position: sticky;
    top: 20px;
    
    .panel-header {
        padding: 20px 24px;
        background: #f8f9fa;
        border-bottom: 1px solid #ecf0f1;
        border-radius: 16px 16px 0 0;
        
        h3 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
        }
    }
    
    .panel-content {
        padding: 24px;
        
        .summary-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 16px;
            
            .label {
                color: #7f8c8d;
                font-size: 14px;
            }
            
            .value {
                font-weight: 500;
                color: #2c3e50;
            }
            
            &.discount .value {
                color: #e74c3c;
            }
        }
        
        .summary-total {
            display: flex;
            justify-content: space-between;
            padding-top: 16px;
            border-top: 1px solid #ecf0f1;
            margin-bottom: 24px;
            
            .label {
                font-size: 16px;
                font-weight: 600;
                color: #2c3e50;
            }
            
            .amount {
                font-size: 20px;
                font-weight: 700;
                color: #e74c3c;
            }
        }
        
        .checkout-actions {
            .checkout-btn {
                width: 100%;
                height: 48px;
                font-size: 16px;
                font-weight: 600;
                background: linear-gradient(45deg, #667eea, #764ba2);
                border: none;
                
                &:hover {
                    transform: translateY(-2px);
                    box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
                }
                
                &:disabled {
                    background: #95a5a6;
                    transform: none;
                    box-shadow: none;
                }
            }
        }
    }
}

.empty-cart {
    text-align: center;
    padding: 60px 20px;
    
    .empty-image {
        color: #95a5a6;
        margin-bottom: 20px;
    }
}



/* 响应式设计 */
@media (max-width: 768px) {
    .cart-content {
        grid-template-columns: 1fr;
    }
    
    .cart-items .cart-item {
        grid-template-columns: auto 1fr auto;
        gap: 12px;
        
        .item-image {
            width: 60px;
            height: 60px;
        }
        
        .item-price,
        .item-quantity,
        .item-subtotal,
        .item-actions {
            grid-column: 2 / -1;
            text-align: left;
            margin-top: 8px;
        }
    }
    

}
</style> 